package com.app.micaihu.view.main.game

import android.content.Intent
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.bean.game.GameCenterEntity
import com.app.micaihu.bean.game.GameDownloadEntity
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.UmEventId
import com.app.micaihu.configure.UmEventId.gamelike
import com.app.micaihu.custom.components.downandupload.DownloadUtils
import com.app.micaihu.db.NewsDBSqlHelper
import com.app.micaihu.db.NewsDBUtil
import com.app.micaihu.utils.DialogUtils.OnDialogBtnClickListener
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.view.lunch.LunchActivity
import com.app.micaihu.view.main.MainActivity
import com.app.micaihu.view.main.game.adapter.GameDownloadAdapter
import com.app.micaihu.view.main.game.adapter.GameLikeDownloadAdapter
import com.app.micaihu.view.main.game.contract.GameContract
import com.app.micaihu.view.main.game.presenter.GamePresenter
import com.app.micaihu.view.utils.DownloadAgainUtils
import com.app.micaihu.view.utils.ViewUtils
import com.app.okhttplib.util.EncryptUtil
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.yanzhenjie.recyclerview.*
import kotlinx.android.synthetic.main.game_download_list.*
import java.io.File
import java.util.*

/**
 * 游戏下载页面
 * Created by linkai on 2017/3/14.
 */
class GameDownloadActivity : BaseMvpActivity<GameContract.View, GamePresenter>(), OnDialogBtnClickListener, GameContract.View {
    override fun getLayoutId(): Int {
        return R.layout.game_download_list
    }

    override fun getPresenter(): GamePresenter {
        return GamePresenter()
    }

    private var swipeMenu: SwipeMenuBridge? = null

    private var position = 0

    private val gameDownloadAdapter: GameDownloadAdapter by lazy {
        GameDownloadAdapter()
    }
    private val gameLikeDownloadAdapter: GameLikeDownloadAdapter by lazy {
        GameLikeDownloadAdapter()
    }

    /**
     * 删除 收藏
     *
     * @param position
     */
    private fun deleteNews(position: Int) {
        this.position = position
        //删除本地缓存和取消下
        if (gameDownloadAdapter.data.size > position && gameDownloadAdapter.data[position] != null) {
            DownloadUtils.getSingleton().showCancleDialog(gameDownloadAdapter.data[position], this)
        }
    }

    override fun onPositiveClick() {
        var newsEntity: GameDownloadEntity? = null
        if (gameDownloadAdapter.data.size > position && gameDownloadAdapter.data[position] != null) {
            try {
                newsEntity = gameDownloadAdapter.data[position]
                if (newsEntity != null) {
                    //删除在列表中 的位置
                    gameDownloadAdapter.data.removeAt(position)
                    //取消网络请求
                    DownloadUtils.getSingleton().cancleRequest()
                    //删除数据库中的数据
                    val sql = "delete from " + NewsDBSqlHelper.GAME_DOWNLOAD + " where _id=" + newsEntity.iGameId
                    NewsDBUtil.getInstance().changeData(sql)
                    DownloadAgainUtils.getManager().cancel(java.lang.Long.valueOf(newsEntity.iGameId).toInt())
                    val unCompletedFile = EncryptUtil.MD5StringTo32Bit(newsEntity.iTag, true)
                    LogUtils.e(unCompletedFile)
                    if (!unCompletedFile.isNullOrEmpty()) {
                        val file = File(DownloadUtils.DOWNLOAD_FILEDIR, unCompletedFile)
                        if (file.exists() && file.isFile) {
                            file.delete()
                        }
                    }
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
        swipeMenu?.closeMenu()
        gameDownloadAdapter.notifyDataSetChanged()
        if (gameDownloadAdapter.data.isEmpty()) {
            gameDownloadAdapter.setEmptyView(getEmptyView(R.drawable.empty_icon_news, "暂无游戏", 200f))
        }
    }

    override fun onNegativeClick() {}

    override fun onResume() {
        super.onResume()
        gameDownloadAdapter.notifyDataSetChanged()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        DownloadUtils.DOWN_LOAD_COUNT = 0
    }

    override fun setData() {
        rvGame.setSwipeMenuCreator(swipeMenuCreator)
        rvGame.setOnItemMenuClickListener(mMenuItemClickListener)
        rvGame.setLayoutManager(LinearLayoutManager(thisContext))
        rvGame.setAdapter(gameDownloadAdapter)
        val gridLayoutManager = GridLayoutManager(thisContext, 4)
        rvGameLike.setLayoutManager(gridLayoutManager)
        rvGameLike.setAdapter(gameLikeDownloadAdapter)

        //小红点清空
        DownloadUtils.DOWN_LOAD_COUNT = 0
        setDbData()
        mPresenter?.gameLike()
    }

    private fun setDbData() {
        val cacheList = NewsDBUtil.getInstance().listCache(null, null, null, NewsDBSqlHelper.GAME_DOWNLOAD, null)
        LogUtils.e("insertGame", "cache->" + cacheList.size)
        if (cacheList != null && !cacheList.isEmpty()) {
            val count = cacheList.size
            val list: MutableList<GameDownloadEntity?> = ArrayList()
            for (i in count - 1 downTo 0) {
                val gameDownloadEntity = GameDownloadEntity()
                gameDownloadEntity.id = cacheList[i]["_id"]
                gameDownloadEntity.name = cacheList[i]["name"]
                gameDownloadEntity.app_url = cacheList[i]["url"]
                gameDownloadEntity.describe = cacheList[i]["desc"]
                gameDownloadEntity.logo = cacheList[i]["logo"]
                gameDownloadEntity.packageName = cacheList[i]["packname"]
                gameDownloadEntity.path = cacheList[i]["path"]
                gameDownloadEntity.appSize = cacheList[i]["size"]
                list.add(gameDownloadEntity)
            }
            if (list.isNotEmpty()) {
                gameDownloadAdapter.setNewInstance(list)
            } else {
                gameDownloadAdapter.setEmptyView(getEmptyView(R.drawable.empty_icon_news, "暂无游戏", 200f))
            }
        } else {
            gameDownloadAdapter.setEmptyView(getEmptyView(R.drawable.empty_icon_news, "暂无游戏", 200f))
        }
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private val swipeMenuCreator: SwipeMenuCreator = object : SwipeMenuCreator {
        override fun onCreateMenu(swipeLeftMenu: SwipeMenu, swipeRightMenu: SwipeMenu, position: Int) {
            LogUtils.e("SwipeMenuCreator", position)
            if (gameDownloadAdapter.hasEmptyView() && position == 0) {

            } else {
                val width = resources.getDimensionPixelSize(R.dimen.dp_90)
                // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
                // 2. 指定具体的高，比如80;
                // 3. WRAP_CONTENT，自身高度，不推荐;
                val height = ViewGroup.LayoutParams.MATCH_PARENT

                // 添加右侧的，如果不添加，则右侧不会出现菜单。
                run {
                    val deleteItem = SwipeMenuItem(this@GameDownloadActivity).setBackground(R.color.common_bg_color_3)
                            .setImage(R.drawable.common_delete_icon)
                            .setTextColor(ColorUtils.getColor(R.color.color666))
                            .setWidth(width)
                            .setHeight(height)
                    swipeRightMenu.addMenuItem(deleteItem) // 添加菜单到右侧。
                }
            }
        }
    }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private val mMenuItemClickListener = OnItemMenuClickListener { menuBridge, adapterPosition -> //            menuBridge.closeMenu();
        val direction = menuBridge.direction // 左侧还是右侧菜单。
        swipeMenu = menuBridge
        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            deleteNews(adapterPosition)
        }
    }

    override fun addListeners() {
        LiveEventBus.get(Config.EventBus.gameLikeDownLoad, Boolean::class.java).observe(this, { gameLikeDownLoad ->
            if (gameLikeDownLoad != null && gameLikeDownLoad) {
                LogUtils.e("insertGame", "gameLikeDownLoad->" + gameLikeDownLoad)
                com.blankj.utilcode.util.ViewUtils.runOnUiThreadDelayed({ setDbData() }, 500)
            }
        })
        gameLikeDownloadAdapter.setOnItemClickListener(com.chad.library.adapter.base.listener.OnItemClickListener { adapter, view, position ->
            MobclickAgentUtils.event(UmEventId.game_click, gamelike)
            val gameCenterEntity: GameCenterEntity = gameLikeDownloadAdapter.getItem(position)
                    ?: return@OnItemClickListener
            val intent = Intent()
            intent.putExtra(Config.Extra.PARAMETER1, gameCenterEntity.articleId)
            intent.setClass(thisContext, GameDetailActivity::class.java)
            startActivity(intent)
        })
    }


    companion object {
        @JvmStatic
        fun insertGame(id: String, title: String, url: String, icon: String, desc: String, packagename: String, path: String, size: String) {
            if (id == null || title == null || url == null || icon == null || desc == null || packagename == null || path == null || size == null) {
                return
            }
            try {
                val sql = "insert into " + NewsDBSqlHelper.GAME_DOWNLOAD +
                        " values ('" + id + "','" + title + "','" + desc + "','" + url + "','" + icon + "','" + packagename + "','" + path + "','" + size + "');"
                val success = NewsDBUtil.getInstance().changeData(sql)
                LiveEventBus.get(Config.EventBus.gameLikeDownLoad, Boolean::class.java).postDelay(true, 500)
                LogUtils.e("insertGame", "insertGame-> $success")

            } catch (e: Exception) {
            }

        }
    }

    override fun handleGameLike(result: BaseBean<List<GameCenterEntity>?>?) {
        super.handleGameLike(result)
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (result.isSuccess()) {
                result.data?.let {
                    gameLikeDownloadAdapter.setNewInstance(it.toMutableList())
                }
            }
        }
    }

    override fun onDestroy() {
        if (!ActivityUtils.isActivityExistsInStack(MainActivity::class.java)) {
            val intent = Intent(this, LunchActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
        super.onDestroy()
    }
}